<script setup lang="ts">
/*global QC*/
import { useSendMobileCode } from '@/composable'
import { bindMobile, loginByQQ } from '@/services/user'
import { useUserStore } from '@/stores'
import type { User } from '@/types/user'
import { codeRules, mobileRules } from '@/utils/rules'
import { showSuccessToast } from 'vant'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const openId = ref('')
// 判断是否需要显示绑定手机页面
const isNeedBind = ref(false)
// 验证码
const code = ref('')
// 登录成功函数
const loginOk = (data: User) => {
  const store = useUserStore()
  // 存储用户信息
  store.setUser(data)
  // 跳转
  router.replace(store.returnUrl || '/user')
  showSuccessToast('登录成功')
  // 删路径
  store.delUrl()
}
// 绑定手机号函数
const loginNo = async () => {
  // 调用绑定手机号接口
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  // 调用登录成功接口
  loginOk(res.data)
}
onMounted(() => {
  if (QC.Login.check()) {
    // 判断是否qq登录
    QC.Login.getMe((id) => {
      openId.value = id
      loginByQQ(id)
        .then((res) => {
          // 成功
          isNeedBind.value = false
          loginOk(res.data)
        })
        .catch(() => {
          // 失败
          isNeedBind.value = true
        })
    })
  }
})
// 发送验证码功能
const mobile = ref('13230000001')
const { form, time, send } = useSendMobileCode(mobile, 'bindMobile')
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        v-model="mobile"
        :rules="mobileRules"
      />
      <van-field
        name="code"
        placeholder="请输入验证码"
        :rules="codeRules"
        v-model="code"
      >
        <template #button>
          <van-button size="small" type="primary" @click="send">
            {{ time ? time + 's后发送验证码' : '发送验证码' }}
          </van-button>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
          @click="loginNo"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '../../styles/login.scss';
</style>

<style lang="scss" scoped></style>
